mylist.append("value")All values in Python are objects
Objects are instances of a data type
Attributes — data the object stores
Methods — actions the object can perform
A class defines a data type
Classes are blueprints for creating objects
int, str, float, list, bool
These are all classes!
mylist.append("value")mystring.upper()myfile.close()Dog ClassLet’s build a class from scratch
We’ll learn:
How to create (instantiate) objects
How to store data (attributes)
How to add behavior (methods)
class Dog:
passThat’s it! We’ve defined a class.
class Dog:
passfido = Dog()
rex = Dog()Call the class like a function to create an instance
fido = Dog()
fido.name = "Fido"
fido.age = 3
fido.breed = "Labrador"print(fido.name)
print(fido.age)Fido 3
# Messy: global variables
fido_name = "Fido"
fido_age = 3
rex_name = "Rex"
rex_age = 5# Clean: attributes
fido.name = "Fido"
fido.age = 3
rex.name = "Rex"
rex.age = 5class Dog:
def bark(self):
print("Woof!")fido = Dog()
fido.bark()Woof!
selfself refers to the object running the method
class Dog:
def bark(self):
print(f"{self.name} says Woof!")fido = Dog()
fido.name = "Fido"
rex = Dog()
rex.name = "Rex"
fido.bark()
rex.bark()Fido says Woof! Rex says Woof!
__init__() Methodclass Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")fido = Dog("Fido", 3)
print(fido.name, fido.age)Fido 3
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
self.hunger = 5 # Scale of 0-10
def bark(self):
print(f"{self.name} says Woof!")
def eat(self):
self.hunger = max(0, self.hunger - 3)
print(f"{self.name} ate! Hunger: {self.hunger}")
def pass_time(self):
self.hunger = min(10, self.hunger + 1)buddy = Dog("Buddy", 2)
buddy.bark()Buddy says Woof!
buddy.hunger5
buddy.eat()
buddy.eat()Buddy ate! Hunger: 2 Buddy ate! Hunger: 0
buddy.pass_time()
buddy.pass_time()
buddy.hunger2
We built a Dog class with:
Instantiation: Dog("Fido", 3)
Attributes: name, age, hunger
Methods: bark(), eat(), pass_time()
class ClassName:
body
Use CamelCase for class names
pass Statementpass does nothing—it’s a placeholder
class Blob:
passUse when you need a body but have nothing to put there
selfclass Greeter:
def greet(self):
print(f"Hi, I'm {self.name}!")self = the object running the method
__init__() Initializes Objectsclass Greeter:
def __init__(self, name):
self.name = nameCalled automatically when object is created
def __init__(self, name, age):
self.name = name # Parameter → Attribute
self.age = age # Parameter → Attribute
self.hunger = 5 # No parameter, default value
# age + 1 # Could use parameter without storing itclass ClassName: to define
ClassName() to instantiate
Methods need self as first parameter
__init__() sets up new objects
Attributes are variables on self
Document your code for others (and future you)
class Dog:
"""A virtual pet dog that tracks hunger.
Attributes:
name (str): the dog's name.
age (int): the dog's age in years.
hunger (int): hunger level from 0 (full) to 10 (starving).
"""def eat(self):
"""Feed the dog, reducing hunger by 3.
Hunger will not go below 0.
"""
self.hunger = max(0, self.hunger - 3)# Correct - docstring first
def greet(self):
"""Say hello."""
print("Hello!")# Wrong - docstring not first
def greet(self):
print("Hello!")
"""This won't work as a docstring."""Class docstrings describe purpose and attributes
Method docstrings describe behavior
Must be the first statement in the body
Use help() to view docstrings
class Dog:
"""A virtual pet dog that tracks hunger.
Attributes:
name (str): the dog's name.
age (int): the dog's age in years.
hunger (int): hunger level from 0 (full) to 10 (starving).
"""
def __init__(self, name, age):
"""Create a new Dog.
Args:
name (str): the dog's name.
age (int): the dog's age in years.
"""
self.name = name
self.age = age
self.hunger = 5 def bark(self):
"""Make the dog bark."""
print(f"{self.name} says Woof!")
def eat(self):
"""Feed the dog, reducing hunger by 3 (minimum 0)."""
self.hunger = max(0, self.hunger - 3)
print(f"{self.name} ate! Hunger: {self.hunger}")
def pass_time(self):
"""Simulate time passing. Increases hunger by 1 (maximum 10)."""
self.hunger = min(10, self.hunger + 1)
def status(self):
"""Print the dog's current status."""
mood = "happy" if self.hunger < 5 else "hungry"
print(f"{self.name} ({self.age} yrs) - Hunger: {self.hunger} - {mood}")Objects combine data and functionality
Classes are blueprints for objects
Attributes store data (self.name)
Methods define behavior (def bark(self))
__init__() initializes new objects
Create your own classes:
BankAccount — balance, deposit(), withdraw()
Student — name, grades list, add_grade(), gpa()
Rectangle — width, height, area(), perimeter()